package com.chen.cos;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(value = "/UserAddServlet")
public class UserAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userid = req.getParameter("userid");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        String url = "jdbc:mysql://localhost:3306/cosplay_community?serverTimezone=UTC";
        String db_name = "root";
        String db_pass = "13574178580";
        String sql = "insert into user(user_id,username,password_hash) values(?,?,?)";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, db_name, db_pass);
            PreparedStatement prep = conn.prepareStatement(sql);
            prep.setString(1, userid);
            prep.setString(2, username);
            prep.setString(3, password);
            int i = prep.executeUpdate();
            if (i > 0) {
                req.getSession().setAttribute("userid", userid);
                req.getRequestDispatcher("登录.jsp").forward(req, resp);
            } else {
                resp.sendRedirect("注册.jsp");
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
